import LayVmodelBase from "./LayVmodelBase.js"
import { logger, tools, runtime } from "./tools.js";


/**Layui下拉绑定 */
class LaySelectVmodel extends LayVmodelBase {
    constructor(elem) {
        super(elem);        
        this.checkFormFilter();
        this.ensureName();
        this.ensureFilter();     
    }

    /**[override] */
    init() {
        if(!super.init()) return;
        var tis = this;
        //订阅value变化
        this.vm.value.subscribe((newValue) => {
            tis.updateSelect(newValue);
        });
        let form = tools.laymod('form');
        form.on(`select`, function (data) {
            var elem = data.elem; // 获得 select 原始 DOM 对象
            var value = data.value; // 获得被选中的值
            var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象

            if ($(elem).attr("lay-filter") === tis.layFilter) {
                tis.vm.value(value);
            }
        });

        tis.updateSelect(tis.vm.value());
        this.inited = true;
    }

    /**[override] */
    loadForAttr() {
        super.loadForAttr();
        let elem = this.element;
        let vm = this.vm;
        //初始化
        if ($(elem).val() !== void 0) {
            vm.value($(elem).val().toString());
        }
    }

    viewModelInit(){
        super.viewModelInit();
        this.vm.value = ko.observable();
    }


    updateSelect(value) {
        var name = this.name;
        if (!name) {
            throw new Error("laySelect绑定元素必须有唯一name属性");
        }
        let form = tools.laymod('form');
        //设置下拉选中
        form.val(this.formFilter, { [name]: value });
    }
}

export default LaySelectVmodel;